<?php
/**
 *
 *
 */
class Yz_Cache_Default
    extends Yz_Class
{

    /**
     *  @var string
     */
    protected static $cachePath;


    /**
     *
     *  @return string
     */
    public static function getCachePath()
    {
        $path =& static::$cachePath;
        if (null === $path) {
            $path = Yz::getConfig()->fetchString('cachePath');
            if (! is_dir($path)) {
                throw new Yz_Cache_Exception('Cache Path does not exist');
            }
        }
        return $path;
    }



    /** Fetch item from cache by identifier(s)
     *  @param string|varargs ident
     *  @return string|null
     */
    public static function fetch( $ident )
    {
        debug();
        $path = static::getCachePath();
        if (! is_array($ident)) {
            $ident = func_get_args();
        }
        $fn = static::determineFileName($ident);
        $file = new Yz_File($fn, $path);
        if ($file->isFile()) {
            $cacheData = $file->getContents();
        } else {
            $cacheData = null;
        }
        return $cacheData;
    }


    /**
     *
     *  @return bool
     */
    public static function update($ident, $content)
    {
        debug();
        $path = static::getCachePath();
        if (! is_array($ident)) {
            $ident = array($ident);
        }
        $fn = static::determineFileName($ident);
        $file = new Yz_File($fn, $path);
        $res = file_put_contents("$file", $content);
        return false !== $res;
    }


    /** remove from cache all entries whose names match {ident}{pattern}.bin
     *      where pattern may contain pattern matching symbols *, {}
     *  @param string|array ident
     *  @param string|null pattern
     *  @return bool
     */
    public static function purge($ident, $pattern=null)
    {
        debug();
        $path = static::getCachePath();
        if (! is_array($ident)) {
            $ident = array($ident);
        }
        if (null !== $pattern) {
            $pattern = '.' . $pattern;
        }
        $fn = static::determineFileName($ident, $pattern);
        $glob = $path . '/' . $fn;
        debug($glob);
        $files = glob($glob, GLOB_NOSORT|GLOB_BRACE);
        if (false !== $files) {
            $res = true;
            foreach ($files as $file) {
                debug("Deleting file {$file}");
                $res = ($res && unlink($file));
            }
        } else {
            $res = false;
        }
        return $res;
    }


    protected static function determineFileName($args, $pattern='')
    {
        $ident = join('.', $args);
        return strtr($ident, '\\*?/[](){}', '__________') . $pattern . '.bin' ;
    }

}
